import React from 'react';
import "./css2/div_demo2.css"

const dataArray=[
  {
    "path": "./",
    "enable": true,
    "dataType": "String",
    "name": "firstName",
    "sampleValue": "Jane",
    "currentValue": "GuoRong"
  },
  {
    "path": "./",
    "enable": true,
    "dataType": "String",
    "name": "lastName",
    "sampleValue": "Citizen",
    "currentValue": "XU"
  },
  {
    "path": "./identityVariables",
    "enable": true,
    "dataType": "String",
    "name": "birthRegistrationState",
    "sampleValue": "VIC",
    "currentValue": ""
  },
  {
    "path": "./identityVariables",
    "enable": true,
    "dataType": "Date",
    "name": "birthRegistrationDate",
    "sampleValue": "08/27/1984",
    "currentValue": null
  },
  {
    "path": "./identityVariables",
    "enable": true,
    "dataType": "String",
    "name": "birthRegistrationNo",
    "sampleValue": "500156",
    "currentValue": ""
  },
  {
    "path": "./",
    "enable": true,
    "dataType": "Date",
    "name": "dateOfBirth",
    "sampleValue": "06/07/1984",
    "currentValue": null
  }
]

const currentData={
    "firstName": "GuoRong",
    "lastName": "XU",
    "gender": "Male",
    "countryCode": "AU",
    "service": [
      "Australia Birth Certificate"
    ],
    "identityVariables": {
      "birthRegistrationState": "",
      "birthRegistrationDate": null,
      "birthRegistrationNo": ""
    },
    "clientReference": "Test_0001",
    "customerId": 661,
    "dateOfBirth": null,
    "consentObtained": {
      "Australia Birth Certificate": true
    }
}

class Test extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      data:dataArray,
      current:currentData,
      textData:currentData,
    }
  }

  handleChange=(path, key, value)=> {
    const{current,data}=this.state;
    // 拷贝
    const newCurrentData = JSON.parse(JSON.stringify(current));
    const newData=JSON.parse(JSON.stringify(data));

    function updateValue(obj, pathArr, key, value) {
      // 当前路径下
      if (pathArr.length === 1 ) {
        obj[key] = value;
      } else{
         // 移出第一个元素
        pathArr.shift();
         if(pathArr.length===0){
           return;
         }
         const nextPath=pathArr[0];
         // 找到下个路径
          if (nextPath in obj) {
            updateValue(obj[nextPath], pathArr, key, value);
          } else {
             // 不存在，则直接创建
            obj[nextPath] = {};
            updateValue(obj[nextPath], pathArr, key, value);
          }
      }
    }
    // 分割成数组
    const pathArr = path.split('/').filter(p => p !== '');
    // 调用
    updateValue(newCurrentData, pathArr, key, value);

    const itemToUpdate = newData.find(item => item.name === key);
    if (itemToUpdate) {
      itemToUpdate.currentValue = value;
    }

    // 修改内容
    this.setState({
      current: newCurrentData,
      data:newData,
    }, () => {
      console.log(`current: ${JSON.stringify(current)}`);
    });
  }



  handleConfirm=() =>{
    const{current}=this.state;
     this.setState({
       textData:current,
     },()=>{
       const{textData}=this.state;
       console.log(`text:${JSON.stringify(textData)}`);
     })
  }

  handleCancel=()=>{
    const{data}=this.state;
    const newData = data.map(item => ({
      ...item, // 浅拷贝当前项
      currentValue: '' // 重置 currentValue
    }));
    this.setState({
       data:newData,
     })
  }

  render(){
    const{textData:text,data}=this.state;
    return (
      <div className="de_main">
        {data.map((item) => (
          <div key={item.name} className="de_col">
            <label><span className="de_setColor">*</span>{item.name}:</label>
            <input
              className="de_input"
              type={item.dataType}
              value={item.currentValue}
              onChange={(event) => this.handleChange(item.path,item.name, event.target.value)}
            />
          </div>
        ))}
        <div className="de_col de_border">
          <button className="de_btn_confirm" onClick={this.handleConfirm}>提交</button>
          <button className="de_btn_cancel" onClick={this.handleCancel}>取消</button>
        </div>
        <div>
          <textarea className="de_text" value={JSON.stringify(text, null, 4)} />
        </div>
      </div>
    );
  }
}

export default Test;
